package com.cetool.autocms.advice;


import com.cetool.autocms.common.BaseResponse;
import com.cetool.autocms.enumeration.OperateEnum;
import com.cetool.autocms.util.BaseResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 自定义全局包装处理器
 *
 * @author 端木超群
 * @date 2021/11/05
 */
@Slf4j
@ControllerAdvice("com.cetool.autocms.controller")
public class CustomWrapHandler < T > implements ResponseBodyAdvice< T > {
    @Override
    public boolean supports(MethodParameter returnType, Class < ? extends HttpMessageConverter< ? >> converterType) {
        return !BaseResponse.class.equals(returnType.getGenericParameterType());
    }

    @Override
    public T beforeBodyWrite(T body, MethodParameter returnType, MediaType selectedContentType,
                             Class < ? extends HttpMessageConverter< ? >> selectedConverterType, ServerHttpRequest request,
                             ServerHttpResponse response) {
        // 写操作成功执行
        if (OperateEnum.class.equals(body.getClass())) {
            return (T) BaseResponseUtil.success((OperateEnum) body);
        }
        // 读操作成功执行
        return (T) BaseResponseUtil.success(body);
    }
}
